package sy.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sy.model.*;
import sy.pageModel.Mtaskrecord;
import sy.pageModel.SessionInfo;
import sy.pageModel.User;
import sy.service.*;
import sy.util.ConfigUtil;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
//@RequestMapping("/dowloadController")
@RequestMapping(value = { "/dowloadController", "/d" })
public class DowloadController extends BaseController  {

	@Autowired
	private UserServiceI userService;
	@Autowired
	private AppinfoServiceI appinfoService;
	@Autowired
	private AppDowloadInfoServiceI appDowloadInfoService;
    @Autowired
    private TaskRecordServiceI taskrecordService;

    @Autowired
    private InviteServiceI inviteService;

   //推荐下级下载app地址
    @RequestMapping("/p")

    public void promotedowload(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{

        String basePath =request.getSession().getServletContext().getRealPath("/");
        String userid=request.getParameter("d");
        String dowloadpath=null;
        dowloadpath="promotedowloadapp/makemoney_"+userid+".apk";

        File file1 = new File(basePath+dowloadpath);

        String localpath=file1.getAbsolutePath();
        File file=new File(localpath);
        System.out.println(file.getAbsolutePath());
        OutputStream toClient =null;
        if(file.exists()){
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setHeader("Content-Type", "application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename="+ file.getName());
            response.addHeader("Content-Length", "" + file.length());
            toClient= response.getOutputStream();
            toClient.write(buffer);
            toClient.flush();
            toClient.close();

            //删除生成的推广apk
//            file.delete();

        }else{
            response.setCharacterEncoding("gbk");
            response.setHeader("Content-Type", "text/html");
            toClient= response.getOutputStream();
            toClient.write("文件已经删除,请重新生成链接".getBytes());
            toClient.flush();
            toClient.close();
        }

    }
    @RequestMapping("/dowloadapk")
    public void dowloadapk(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{

        String basePath =request.getSession().getServletContext().getRealPath("/");
        String dowloadpath=request.getParameter("dowloadpath");


        File file1 = new File(basePath+dowloadpath);

        String localpath=file1.getAbsolutePath();
        File file=new File(localpath);

        OutputStream toClient =null;
        if(file.exists()){
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setHeader("Content-Type", "application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename="+ file.getName());
            response.addHeader("Content-Length", "" + file.length());
            toClient= response.getOutputStream();
            toClient.write(buffer);
            toClient.flush();
            toClient.close();

        }else{
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");
            toClient= response.getOutputStream();
            toClient.write("文件不存在".getBytes());
            toClient.flush();
            toClient.close();
        }

    }
    //userid:邀请人id inviteuserid：被邀请人id 获得被邀请人的所有父级邀请人id 向上面找三级
    public List<Tinviterecord> getTGClass(String userid)throws Exception{

        List<Tinviterecord> tinviterecords=new ArrayList<Tinviterecord>();

        Tinviterecord tinviterecord1=null;
        Tinviterecord tinviterecord2=null;
        Tinviterecord tinviterecord3=null;
        //如果不为空表示存在上级推广  第一级
        tinviterecord1=inviteService.getUpClass(userid);

        if(tinviterecord1!=null){
            tinviterecords.add(tinviterecord1);
            //找第二级
            tinviterecord2= inviteService.getUpClass(tinviterecord1.getUserid());
            if(tinviterecord2!=null){
                tinviterecords.add(tinviterecord2);
                //找第三级
                tinviterecord3= inviteService.getUpClass(tinviterecord2.getUserid());
                if(tinviterecord3!=null){
                    tinviterecords.add(tinviterecord3);
                }
            }

        }

        return tinviterecords;
    }
    //三级分成
    public void getMoenyTo(Integer pub,SessionInfo sessionInfo){
        try{
            //定义三级推广用户所加积分变量
            long gold1=0;

            Tinviterecord tinviterecord=inviteService.getUpClass(sessionInfo.getUserid()+"");
            if(tinviterecord!=null){//改用户是被邀请  第一次做人要 7W
                //判断是否第一次做任务
                List<Taskrecord> taskrecords= taskrecordService.gettask(sessionInfo.getUserid());
                if(taskrecords.size()<=0){//第一次做任务
                    gold1+=70000;

                }
                //获得这个用户推广向上三级 用户
                List<Tinviterecord> tinviterecords= getTGClass(sessionInfo.getUserid()+"");
                long gold=0;
                for(int i=0;i<tinviterecords.size();i++){
                    Tuser u = null;
                    User user = new User();
                    if(i==0){
                        u=userService.getUserByUserId(tinviterecords.get(i).getUserid());
                        double t= pub*0.35;
                        gold= (long)t+gold1;//加上第一次做任务积分 没有加0

                        user.setId(u.getId());
                        user.setTotalscore(u.getTotalscore()+(int)gold);
                        user.setUnchangedscore(u.getUnchangedscore()+(int)gold);
                        userService.editotlescore(user);

                        //     usercontrol.updatetotalscore(u.getId(),(int)gold , 1);//更新积分

                    }else if(i==1){
                        u=userService.getUserByUserId(tinviterecords.get(i).getUserid());
                        double t= pub*0.1;

                        user.setId(u.getId());
                        user.setTotalscore(u.getTotalscore()+(int)t);
                        user.setUnchangedscore(u.getUnchangedscore()+(int)t);
                        userService.editotlescore(user);

                    }else if(i==2){
                        u=userService.getUserByUserId(tinviterecords.get(i).getUserid());
                        double t= pub*0.05;
                        user.setId(u.getId());
                        user.setTotalscore(u.getTotalscore()+(int)t);
                        user.setUnchangedscore(u.getUnchangedscore()+(int)t);
                        userService.editotlescore(user);

                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @RequestMapping("/dowload")  //官方推荐下载
	  public void uploadad(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{

       final   SessionInfo sessionInfo = (SessionInfo)session.getAttribute(ConfigUtil.getSessionInfoName());

		String basePath =request.getSession().getServletContext().getRealPath("/");
          String dowloadpath=request.getParameter("dowloadpath");
			String userid=request.getParameter("userid");
			String appid = request.getParameter("appid");


            Tuser tuser=userService.getUserByUserId(userid);
            final User user=new User();
            BeanUtils.copyProperties(tuser,user);
			
			File file1 = new File(basePath+dowloadpath);
			
			String localpath=file1.getAbsolutePath();
			File file=new File(localpath);

			OutputStream toClient =null;
			if(file.exists()){
				InputStream fis = new BufferedInputStream(new FileInputStream(file));
				byte[] buffer = new byte[fis.available()];
				fis.read(buffer);
				fis.close();
				// 清空response
				response.reset();
				// 设置response的Header
				response.setHeader("Content-Type", "application/octet-stream");
				response.addHeader("Content-Disposition", "attachment;filename="+ file.getName());
				response.addHeader("Content-Length", "" + file.length());
				toClient= response.getOutputStream();
				toClient.write(buffer);
				toClient.flush();
				toClient.close();
				
				//判断是否已经下载改apk
				List<Tappdowloadinfo> tappdowloadinfo=appDowloadInfoService.getTappdowloadinfo(userid,appid);

				Tappinfo tappinfo=appinfoService.get(appid);
				
				if(tappdowloadinfo.size()>0){//不增加积分
					
				}else{//增加积分

                    if(user.getTotalscore()==null){
                        user.setTotalscore(Integer.parseInt(tappinfo.getIntegral()));
                    }else{
                        user.setTotalscore(user.getTotalscore()+Integer.parseInt(tappinfo.getIntegral()));
                    }
                    if(user.getUnchangedscore()==null){
                        user.setUnchangedscore(Integer.parseInt(tappinfo.getIntegral()));
                    }else{
                        user.setUnchangedscore(user.getUnchangedscore()+Integer.parseInt(tappinfo.getIntegral()));
                    }
                    final int socre=Integer.parseInt(tappinfo.getIntegral());

                    //开启线程
                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            long startime=new Date().getTime();
                            long currenttime=0;
                            boolean tag=true;
                            while (tag){

                                try {

                                    Thread.sleep(5*60*1000);

                                    currenttime=new Date().getTime();

                                    if(currenttime>=startime+5*60*1000){

                                        userService.editotlescore(user);
                                        //三级分成
                                        getMoenyTo(socre,sessionInfo);

                                        tag=false;
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                        }
                    }).start();
					
				}
				//添加下载记录
				Tappdowloadinfo tappdowloadinfo2=new Tappdowloadinfo();
				tappdowloadinfo2.setUserid(userid);
				tappdowloadinfo2.setDownloadtime(new Date().getTime()+"");
				tappdowloadinfo2.setAppid(appid);
				appDowloadInfoService.add(tappdowloadinfo2);
                Mtaskrecord task = new Mtaskrecord();

                //添加任务记录
                task.setTaskType("9");
                task.setUserid(Long.parseLong(userid));
                task.setScore(Integer.parseInt(tappinfo.getIntegral()));

                taskrecordService.add(task);

			}else{
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Type", "text/html");
				toClient= response.getOutputStream();
				toClient.write("文件不存在".getBytes());
				toClient.flush();
				toClient.close();
			}
		
	  }
	
	@RequestMapping("/upload")
	//@ResponseBody
	  public String upload(@RequestParam("filetype") String filetype,@RequestParam MultipartFile file,HttpServletRequest request) throws Exception{
		ServletContext context=request.getSession().getServletContext();
		String realpath = context.getRealPath("/upload");
		File filelocal = new File(realpath);
		if(!filelocal.exists()) filelocal.mkdirs();
		String filename="error";
		String hz=null;
		String uploadImageFileName=file.getOriginalFilename();
		
		
		if(!"".equals(uploadImageFileName)&&uploadImageFileName!=null){
			hz=uploadImageFileName.substring(uploadImageFileName.lastIndexOf(".")+1);
		}
		
		if(filetype.equals("1")){//android
			filename="Android."+hz;
		}else{//ios
			filename="IOS."+hz;
		}
		SaveFileFromInputStream(file.getInputStream(),filelocal.getAbsolutePath(),filename);//保
		//FileUtils.copyFile(file, new File(filelocal, filename));
		return "/admin/uploadfile";
	  }
	public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException
	   {      
	       FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);
	   
	       byte[] buffer =new byte[1024*1024];
	       int bytesum = 0;
	       int byteread = 0; 
	       while ((byteread=stream.read(buffer))!=-1)
	       {
	          bytesum+=byteread;
	          fs.write(buffer,0,byteread);
	          fs.flush();
	       } 
	       fs.close();
	       stream.close();      
	   }       

	//删除文件
	@ResponseBody
	@RequestMapping("/deleteapp")
	public void deleteapp(@RequestParam("appname") String  appname,HttpServletRequest request,HttpServletResponse response){
		PrintWriter out=null;
		JSONObject jsonObject=new JSONObject();
		try {
				out = (PrintWriter)response.getWriter();
				
				ServletContext context=request.getSession().getServletContext();
				String realpath = context.getRealPath("/upload");
				File file = new File(realpath);
				File[] files=file.listFiles();
				
				for(File f:files){
					if(f.getName().indexOf(appname)>-1){
						//删除文件
						f.delete();
						jsonObject.put("msg", true);
						break;
					}
				}
			} catch (IOException e) {
				jsonObject.put("msg", false);
				e.printStackTrace();
			}
			out.print(jsonObject);
			out.flush();
			out.close();
	}
	
	 //获取已经上传的app文件列表
	@ResponseBody
	@RequestMapping("/applist")
	public  void applist(HttpServletRequest request,HttpServletResponse response){
		ServletContext context=request.getSession().getServletContext();
		String realpath = context.getRealPath("/upload");
		File file = new File(realpath);
		File[] appfiles=file.listFiles();
		
		JSONArray array=new JSONArray();
		JSONObject jsonObject=null;
		String path = request.getContextPath();
		String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

		if(appfiles!=null){
			for(int i=0;i<appfiles.length;i++){
				jsonObject=new JSONObject();
				jsonObject.put("filename", appfiles[i].getName());
				jsonObject.put("filepath", basePath+"upload/"+appfiles[i].getName());

				array.add(jsonObject);
			}
		}
		
		PrintWriter out;
		try {
			out = (PrintWriter)response.getWriter();
				out.print(array);
				out.flush();
			out.close();
				
			} catch (IOException e) {
			e.printStackTrace();
			}
		
		
	}


}
